#include "net/poll_thread_pool.h"
#include "net/poll_thread.h"
#include "net/poller.h"

DEFINE_int32(worker_cnt, 4, "thread pool worker number");

namespace net {

PollThreadPool::PollThreadPool(Poller* base_poll)
    : index_(-1), base_poll_(base_poll) {
  InitThread();
}

Poller* PollThreadPool::getPoller() {
  if (threads_.empty()) return base_poll_.get();
  CHECK(index_ != -1 && index_ < threads_.size());

  Poller* poller = threads_[index_]->Poll();
  if (++index_ == FLAGS_worker_cnt - 1) {
    index_ = 0;
  }

  return poller;
}

void PollThreadPool::InitThread() {
  for (int i = 0; i < FLAGS_worker_cnt; ++i) {
    threads_.push_back(new PollThread);
  }

  index_ = 0;
}

void PollThreadPool::Start() {
  base_poll_->Loop();
}

}
